<template>
  <div class="content-page">
    <div class="header flex justify-between items-center mb-8">
      <div class="search-filter-container flex items-center space-x-4">
        <input
          type="text"
          placeholder="搜索证书..."
          class="search-input border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-blue-500 focus:border-blue-500"
        />
        <select
          class="filter-select border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-blue-500 focus:border-blue-500"
        >
          <option value="all">全部类型</option>
          <!-- 这里可以添加更多筛选选项 -->
        </select>
        <button
          class="filter-button bg-blue-500 text-white rounded-md px-4 py-2 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50"
        >
          筛选
        </button>
      </div>
      <el-button type="primary" @click="showDialog = true">上传认证</el-button>
    </div>

    <div class="certificate-gallery">
      <div
        class="certificate-container"
        v-for="(certificate, index) in certificates"
        :key="index"
      >
        <h3>{{ certificate.name }}</h3>
        <img
          :src="certificate.activityImg"
          :alt="`Certificate Image ${index + 1}`"
          style="width: 400px; height: 240px"
        />
        <div class="certificate-info">
          <p><strong>活动名称:</strong> {{ certificate.activityName }}</p>
          <p><strong>活动类型:</strong> {{ certificate.activityTypeName }}</p>
          <p><strong>活动规模:</strong> {{ certificate.scaleName }}</p>
          <p><strong>活动角色:</strong> {{ certificate.position === 0? '领导者' : '成员' }}</p>
          <p><strong>组织单位:</strong> {{ certificate.organization }}</p>
          <p><strong>领导反馈:</strong> {{ certificate.feedback }}</p>
          <p><strong>开始时间:</strong> {{ formatDate(certificate.startTime) }}</p>
          <p><strong>结束时间:</strong> {{ formatDate(certificate.endTime) }}</p>
          <p><strong>活动描述:</strong> {{ certificate.description }}</p>
        </div>
        <div class="actions-container">
          <template v-if="certificate.status === 0">
            <span class="flex items-center gap-1 text-orange-500">
              <i class="fas fa-clock"></i>
              <span class="text-sm">待审核</span>
            </span>
          </template>
          <template v-if="certificate.status === 1">
            <span class="flex items-center gap-1 text-green-600">
              <i class="iconfont icon-gou1"></i>
              <span class="text-sm">审核通过</span>
            </span>
          </template>
          <template v-if="certificate.status === 2">
            <span class="flex items-center gap-1 text-red-600">
              <i class="iconfont icon-chacha"></i>
              <span class="text-sm">审核未通过</span>
            </span>
          </template>
          <button class="edit-button" @click="showEditDialog(certificate)">修改</button>
          <button class="delete-button" @click="confirmRemoveCertificate(certificate.id)">删除</button>
        </div>
      </div>
    </div>

    <div v-if="showDialog" class="dialog-overlay fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
      <div class="dialog-content bg-white rounded-tl-lg rounded-bl-lg w-[80vw] max-w-[800px] p-8">
        <div class="dialog-header mb-6">
          <h2 class="text-xl font-medium">提交活动信息</h2>
        </div>
        <div class="dialog-body">
          <form @submit.prevent="handleSubmit">
            <div class="form-item mb-4">
              <label class="required-label block mb-2">活动名称:</label>
              <el-input
                v-model="formData.activityName"
                placeholder="请输入活动名称"
                class="w-full text-sm"
              />
            </div>
            <div class="form-item mb-4">
              <label class="required-label block mb-2">活动类型:</label>
              <el-select
                v-model="formData.activityTypeId"
                placeholder="请选择活动类型"
                class="w-full text-sm"
              >
                <el-option
                  v-for="(activityType, index) in activityTypeList"
                  :key="index"
                  :label="activityType.activityTypeName"
                  :value="activityType.id"
                />
              </el-select>
            </div>
            <div class="form-item mb-4">
              <label class="required-label block mb-2">活动规模:</label>
              <el-select
                v-model="formData.scaleId"
                placeholder="请选择活动规模"
                class="w-full text-sm"
              >
                <el-option
                  v-for="(dicScale, index) in dicScaleList"
                  :key="index"
                  :label="`${dicScale.scaleName}(${dicScale.scaleScope})`"
                  :value="dicScale.id"
                />
              </el-select>
            </div>
            <div class="form-item mb-4">
              <label class="required-label block mb-2">组织单位:</label>
              <el-input
                v-model="formData.organization"
                placeholder="请输入组织名称"
                class="w-full text-sm"
              />
            </div>
            <div class="form-item mb-4">
              <label class="required-label block mb-2">所担任角色:</label>
              <el-radio-group v-model="formData.position" class="flex gap-6">
                <el-radio :label="0">领导者</el-radio>
                <el-radio :label="1">成员</el-radio>
              </el-radio-group>
            </div>
            <div class="form-item mb-4">
              <label class="required-label block mb-2">活动时间:</label>
              <div class="flex items-center gap-4">
                <el-date-picker
                  v-model="formData.startTime"
                  type="date"
                  placeholder="选择开始时间"
                  class="flex-1 text-sm"
                />
                <span class="text-gray-400">-</span>
                <el-date-picker
                  v-model="formData.endTime"
                  type="date"
                  placeholder="选择结束时间"
                  class="flex-1 text-sm"
                />
              </div>
            </div>
            <div class="form-item mb-4">
              <label class="required-label block mb-2">活动内容:</label>
              <el-input
                v-model="formData.description"
                type="textarea"
                :maxlength="50"
                :rows="4"
                placeholder="请输入活动内容"
                show-word-limit
                class="w-full text-sm"
              />
            </div>
            <div class="form-item mb-4">
              <label class="required-label block mb-2">活动收获:</label>
              <el-input
                v-model="formData.skillsGained"
                type="textarea"
                :maxlength="50"
                :rows="4"
                placeholder="请输入活动收获"
                show-word-limit
                class="w-full text-sm"
              />
            </div>
            <div class="form-item mb-4">
              <label class="required-label block mb-2">领导反馈:</label>
              <el-input
                v-model="formData.feedback"
                type="textarea"
                :maxlength="50"
                :rows="4"
                placeholder="请输入领导评价"
                show-word-limit
                class="w-full text-sm"
              />
            </div>
            <div class="form-item mb-6">
              <label class="required-label block mb-2">图片证明材料:</label>
              <div
                class="upload-area border-2 border-dashed border-gray-200 rounded-lg p-6 text-center cursor-pointer hover:border-blue-400 transition-colors"
                @click="triggerUpload"
              >
                <el-icon class="text-gray-400 text-2xl mb-2">
                  <Plus />
                </el-icon>
                <input
                  ref="fileInput"
                  type="file"
                  class="hidden"
                  accept="image/*"
                  @change="handleFileChange"
                />
                <div class="text-gray-500 text-sm">点击或拖拽上传图片(图片需要重新上传)</div>
                <div class="text-gray-400 text-xs mt-1">图片尺寸规则:A4纸为准,大小不大于1M</div>
              </div>
              <div v-if="imagePreview" class="mt-4">
                <img
                  :src="imagePreview"
                  alt="预览图片"
                  class="w-full h-auto rounded-lg"
                />
              </div>
            </div>
            <div class="dialog-footer flex justify-end gap-4">
              <el-button
                @click="handleCancel"
                class="!rounded-button whitespace-nowrap"
              >
                返回
              </el-button>
              <el-button
                type="primary"
                @click="handleSubmit"
                :disabled="!isFormValid"
                class="!rounded-button whitespace-nowrap"
              >
                提交
              </el-button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getActivity,
  deleteActivity,
  getActivityTypeList,
  getDicScaleList
} from '@/api/student/certification/stuActivity';
import { getToken } from '@/utils/auth';
import axios from 'axios';

const showDialog = ref(false);
const fileInput = ref(null);
const formData = ref({
  id: '',
  activityName: '',
  activityTypeId: '',
  scaleId: '',
  startTime: '',
  endTime: '',
  organization: '',
  description: '',
  skillsGained: '',
  feedback: '',
  position: '',
  file: null
});
const isFormValid = computed(() => {
  return (
    formData.value.activityName &&
    formData.value.activityTypeId &&
    formData.value.scaleId &&
    formData.value.startTime &&
    formData.value.endTime &&
    formData.value.organization &&
    formData.value.description &&
    formData.value.skillsGained &&
    formData.value.feedback &&
    formData.value.position!== '' &&
    formData.value.file
  );
});

const triggerUpload = () => {
  fileInput.value?.click();
};

const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
};

const imagePreview = ref(null);

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    formData.value.file = file;
    if (file.size > 1024 * 1024) {
      ElMessage.error('文件大小不能超过1M');
      formData.value.file = null;
      return;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreview.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

const handleSubmit = async () => {
  if (!isFormValid.value) {
    ElMessage.warning('请填写完整所有必填项');
    return;
  }

  const form = new FormData();
  form.append('images', formData.value.file);
  form.append(
    'activityDto',
    JSON.stringify({
      id: formData.value.id,
      activityName: formData.value.activityName,
      activityTypeId: formData.value.activityTypeId,
      scaleId: formData.value.scaleId,
      startTime: formData.value.startTime,
      endTime: formData.value.endTime,
      organization: formData.value.organization,
      description: formData.value.description,
      skillsGained: formData.value.skillsGained,
      feedback: formData.value.feedback,
      position: formData.value.position
    })
  );

  try {
    const token = getToken();
    const response = await axios.post(
      'http://localhost:8081/certificateAuthority/addActivity',
      form,
      {
        headers: {
          token: `${token}`,
          'Content-Type': 'multipart/form-data'
        }
      }
    );

    if (response.data.code === 200) {
      ElMessage.success('提交成功');
      formData.value = {
        id: '',
        activityName: '',
        activityTypeId: '',
        scaleId: '',
        startTime: '',
        endTime: '',
        organization: '',
        description: '',
        skillsGained: '',
        feedback: '',
        position: '',
        file: null
      };
      imagePreview.value = null;
      showDialog.value = false;
      fetchCertificates();
    } else {
      ElMessage.error(response.data.msg || '提交失败，请稍后重试');
    }
  } catch (error) {
    ElMessage.error('提交时发生错误');
  }
};

const handleCancel = () => {
  showDialog.value = false;
  formData.value = {
    id: '',
    activityName: '',
    activityTypeId: '',
    scaleId: '',
    startTime: '',
    endTime: '',
    organization: '',
    description: '',
    skillsGained: '',
    feedback: '',
    position: '',
    file: null
  };
  imagePreview.value = null;
  ElMessage.info('已取消');
};

const certificates = ref([]);

const fetchCertificates = () => {
  getActivity()
    .then((response) => {
      certificates.value = response;
    })
    .catch((error) => {
      ElMessage.error('查询数据时发生错误');
      console.error(error);
    });
};

onMounted(() => {
  fetchCertificates();
});

const confirmRemoveCertificate = (id) => {
  ElMessageBox.confirm(
    '您确定要删除这个活动记录吗？此操作不可逆！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      removeCertificate(id);
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      });
    });
};

const removeCertificate = (id) => {
  deleteActivity(id)
    .then((response) => {
      ElMessage.success('删除成功');
      fetchCertificates();
    })
    .catch((error) => {
      ElMessage.error('删除失败');
      console.error(error);
    });
};

const activityTypeList = ref([]);
const dicScaleList = ref([]);
const loading = ref(false);

watch(showDialog, async (newVal) => {
  if (newVal) {
    try {
      loading.value = true;
      const res = await getActivityTypeList();
      const res1 = await getDicScaleList();
      activityTypeList.value = res;
      dicScaleList.value = res1;
    } catch (error) {
      ElMessage.error('获取列表失败');
    } finally {
      loading.value = false;
    }
  } else {
    formData.value = {
      id: '',
      activityName: '',
      activityTypeId: '',
      scaleId: '',
      startTime: '',
      endTime: '',
      organization: '',
      description: '',
      skillsGained: '',
      feedback: '',
      position: '',
      file: null
    };
  }
});

const showEditDialog = (certificate) => {
  formData.value = {
    id: certificate.id,
    activityName: certificate.activityName,
    activityTypeId: certificate.activityTypeId,
    scaleId: certificate.scaleId,
    startTime: certificate.startTime,
    endTime: certificate.endTime,
    organization: certificate.organization,
    description: certificate.description,
    skillsGained: certificate.skillsGained,
    feedback: certificate.feedback,
    position: certificate.position,
    file: null
  };
  imagePreview.value = certificate.activityImg;
  showDialog.value = true;
};
</script>

<style scoped>
.required-label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}

.dialog-overlay {
  z-index: 1000;
}

.dialog-content {
  width: 90vw;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  background: #fff;
  border-radius: 1rem 0 0 1rem;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.dialog-content::-webkit-scrollbar {
  width: 8px;
}

.dialog-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 1rem;
}

.dialog-content::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 1rem;
}

.dialog-content::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.certificate-gallery {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1rem;
  justify-items: center;
}

.certificate-container {
  position: relative;
  border-radius: 0.1rem;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  padding: 0.5rem;
  text-align: center;
  width: 400px;
  /* max-width: 300px; */
}

h3 {
  font-size: 1.25rem;
  color: #333;
}

img {
  display: block;
  margin: 0.1rem auto;
  border-radius: 0.5rem;
  width: 400px;
  height: 250px;
}

.certificate-info {
  text-align: left;
  margin-top: 0.2rem;
  overflow-wrap: break-word;
  word-break: break-all;
  max-width: 260px;
}

p {
  font-size: 1rem;
  color: #00796b;
  margin: 0.3rem 0;
}

.actions-container {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  margin-top: 0.5rem;
  justify-content: flex-end;
}

.edit-button {
  background-color: #2196f3;
  color: white;
  border: none;
  padding: 0.3rem 0.5rem;
  border-radius: 0.5rem;
  cursor: pointer;
  margin-right: 0.3rem;
}

.edit-button:hover {
  background-color: #1976d2;
}

.delete-button {
  background-color: red;
  color: white;
  border: none;
  padding: 0.3rem 0.5rem;
  border-radius: 0.5rem;
  cursor: pointer;
}

.delete-button:hover {
  background-color: darkred;
}

.search-input {
  width: 80%;
  max-width: 400px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px 12px;
}

.search-input:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
  border-color: #3b82f6;
}

.filter-select {
  width: auto;
  min-width: 150px;
  padding: 0.5rem 0.75rem; /* 调整内边距，确保和输入框、按钮高度一致 */
  line-height: 1.25; /* 调整行高，确保文字垂直居中 */
}

.filter-button {
  width: auto;
  min-width: 80px;
  padding: 0.5rem 1rem; /* 调整内边距，确保和输入框、选择框高度一致 */
  line-height: 1.25; /* 调整行高，确保文字垂直居中 */
}

.upload-area {
  transition: border-color 0.3s ease;
}

.upload-area:hover {
  border-color: #3b82f6;
}

.el-button {
  transition: all 0.3s ease;
}

.el-button:hover {
  transform: scale(1.05);
}
.certificate-info p {
  font-size: 1rem;
  color: #000; /* 原来为#00796b，现改为黑色#000 */
  margin: 0.15rem 0;
  white-space: nowrap; 
  overflow: hidden; 
  text-overflow: ellipsis; 
}


</style>    